package com.egreen.pointsmall.utils;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;


import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 *产生二维码工具类
 */
public class codepicture {

    public boolean CreateCode(String content, String path) throws Exception {
        int width = 300;
        int height = 300;
        String format = "jpg";
        Map<EncodeHintType, Object> map = new HashMap<>();
        map.put(EncodeHintType.CHARACTER_SET, "utf-8");
        //容错率等级L>M>Q>H,等级越高，所需要的扫描时间越长，但是准确率越高
        map.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
        map.put(EncodeHintType.MARGIN, 2);
        BitMatrix encode = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height, map);
        Path path1 = FileSystems.getDefault().getPath(path);
        MatrixToImageWriter.writeToPath(encode, format, path1);
        return true;
    }

    public static void main(String[] args) throws Exception {
        //创建一个不会重复的UUID
        String uuid = UUID.randomUUID().toString();
        //去掉 - 并截取前8位
        String name = uuid.replace("-", "").substring(0, 8);
        //二维码存放的路径
        String path = "D:\\code\\" + name + ".jpg";
        //使用反射代替new关键字
        codepicture a=new codepicture();
        boolean b=a.CreateCode("人在美国，刚下飞机", path);
        if (b) {
            System.out.println("二维码创建成功！");
            System.out.println(path);
        } else {
            System.out.println("失败！");
        }
    }

}
